package server;

import java.io.Serializable;
import java.security.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.*;

public class GenrateSharedKey implements Serializable{

    SecretKey aesKey;

    public GenrateSharedKey() {
        try {

            KeyGenerator keygen = KeyGenerator.getInstance("DES");
            aesKey = keygen.generateKey();
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(GenrateSharedKey.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    static byte[] encryptData(String o, Key key) {
        try {

            Cipher aesCipher = Cipher.getInstance("DES/CBC/PKCS5P");
            aesCipher.init(Cipher.ENCRYPT_MODE, key);
            
            byte[] ciphertext = aesCipher.doFinal(o.getBytes());
            return ciphertext;

        } catch (IllegalBlockSizeException ex) {
            Logger.getLogger(GenrateSharedKey.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BadPaddingException ex) {
            Logger.getLogger(GenrateSharedKey.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(GenrateSharedKey.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(GenrateSharedKey.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchPaddingException ex) {
            Logger.getLogger(GenrateSharedKey.class.getName()).log(Level.SEVERE, null, ex);
        }

        // If there is no cipher return null ; 
        return null;
    }

    static byte[] decrypt(byte[] o, Key key) {
        byte[] decData = null;
        try {
            Cipher encData = Cipher.getInstance("DES/CBC/PKCS5P");
            encData.init(Cipher.DECRYPT_MODE, key);
            
            byte bytes [] = new byte[1024];
            for (int i = 0; i < o.length; i+=1024) {
                encData.update(o, i, 1024);
            }

            decData = encData.doFinal();
        } catch (IllegalBlockSizeException ex) {
            Logger.getLogger(GenrateSharedKey.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BadPaddingException ex) {
            Logger.getLogger(GenrateSharedKey.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(GenrateSharedKey.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(GenrateSharedKey.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchPaddingException ex) {
            Logger.getLogger(GenrateSharedKey.class.getName()).log(Level.SEVERE, null, ex);
        }
        return decData;
    }

    public void setAesKey(SecretKey aesKey) {
        this.aesKey = aesKey;
    }

    public SecretKey getAesKey() {
        return aesKey;
    }
}
